package com.music.note_android.ui.editor

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.View
import kotlin.math.max
import kotlin.math.min

/**
 * 自定义画布视图，支持无限画布、压感手写、多种画笔工具
 * 这是画布编辑模块的核心组件，负责处理所有的绘制和交互逻辑
 */
class DrawingCanvasView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 绘制引擎
    private lateinit var canvasManager: CanvasManager
    private lateinit var drawingEngine: DrawingEngine
    private lateinit var pointRenderingEngine: PointRenderingEngine
    private lateinit var gestureHandler: GestureHandler
    private lateinit var pressureHandler: PressureHandler
    
    // 当前绘制工具
    private var currentTool: DrawingTool = DrawingTool.PEN
    
    // 当前画笔颜色
    private var currentColor: Int = Color.BLACK
    
    // 当前画笔粗细
    private var currentWidth: Float = 6f
    
    // 压感相关
    private var supportsPressure = false
    private var pressureSensitivity = 1.0f
    private var enablePressureResponse = true // 启用压感响应
    private var pressureMinWidth = 0.5f // 压感最小宽度倍数
    private var pressureMaxWidth = 2.0f // 压感最大宽度倍数
    
    // 缩放手势检测器
    private val scaleGestureDetector = ScaleGestureDetector(context, ScaleListener())
    
    // 当前是否处于绘制模式
    private var isDrawingMode = true
    
    // 当前笔画
    private var currentStroke: Stroke? = null
    private var currentPointDrawing: PointDrawing? = null
    
    // 渲染模式控制
    private var usePointBasedRendering = true
    
    // 画布变换矩阵
    private val canvasMatrix = Matrix()
    
    // 临时矩阵用于计算
    private val tempMatrix = Matrix()
    
    // 画布缩放比例
    private var scaleFactor = 1.0f
    
    // 画布偏移量
    private var offsetX = 0f
    private var offsetY = 0f
    
    // 最小和最大缩放比例
    private val minScale = 0.1f
    private val maxScale = 5.0f
    
    // 上一次触摸点坐标
    private var lastTouchX = 0f
    private var lastTouchY = 0f
    
    init {
        // 初始化画布设置
        initCanvas()
        // 初始化组件
        initializeComponents()
    }
    
    /**
     * 初始化画布设置
     */
    private fun initCanvas() {
        // 启用硬件加速以提高绘制性能
        setLayerType(LAYER_TYPE_HARDWARE, null)
        
        // 设置画布为可聚焦，以便接收触摸事件
        isFocusable = true
        isFocusableInTouchMode = true
    }
    
    /**
     * 初始化画布组件
     */
    private fun initializeComponents() {
        // 初始化画布管理器
        canvasManager = CanvasManager()
        
        // 初始化绘制引擎
        drawingEngine = DrawingEngine()
        drawingEngine.initialize()
        
        // 初始化点渲染引擎
        pointRenderingEngine = PointRenderingEngine()
        
        // 初始化手势处理器
        gestureHandler = GestureHandler()
        gestureHandler.initialize(this)
        gestureHandler.setGestureListener(createGestureListener())
        
        // 初始化压感处理器
        pressureHandler = PressureHandler()
        pressureHandler.initialize()
        
        // 应用推荐的压感设置
        pressureHandler.setPressureConfiguration(pressureHandler.getRecommendedSettings())
        
        // 检测设备压感支持
        supportsPressure = pressureHandler.isDevicePressureSupported()
        
        // 设置压感响应参数
        configurePressureResponse()
    }
    
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        
        // 绘制网格（在变换之前绘制，保持固定大小）
        if (showGrid) {
            drawGrid(canvas)
        }
        
        // 绘制标尺（在变换之前绘制，保持固定大小）
        if (showRuler) {
            drawRuler(canvas)
        }
        
        // 根据渲染模式选择渲染引擎
        if (usePointBasedRendering) {
            // 使用点渲染引擎渲染画布内容
            // 保存画布状态并应用变换
            canvas.save()
            canvas.translate(canvasOffsetX, canvasOffsetY)
            canvas.scale(canvasScale, canvasScale)
            
            // 渲染所有点绘画
            canvasManager.getAllPointDrawings().forEach { pointDrawing ->
                pointRenderingEngine.renderPointDrawing(
                    canvas = canvas,
                    pointDrawing = pointDrawing,
                    scale = canvasScale
                )
            }
            
            // 渲染当前正在绘制的点绘画
            currentPointDrawing?.let { pointDrawing ->
                pointRenderingEngine.renderPointDrawing(
                    canvas = canvas,
                    pointDrawing = pointDrawing,
                    scale = canvasScale
                )
            }
            
            // 恢复画布状态
            canvas.restore()
        } else {
            // 使用传统线条渲染引擎
            drawingEngine.renderCanvas(
                 canvas = canvas,
                 canvasManager = canvasManager,
                 viewWidth = width,
                 viewHeight = height,
                 offsetX = canvasOffsetX,
                 offsetY = canvasOffsetY,
                 scale = canvasScale
             )
        }
        
        // 绘制UI层（工具栏等）
        drawUI(canvas)
    }
    
    /**
     * 绘制UI层内容
     */
    private fun drawUI(canvas: Canvas) {
        // 这里可以绘制一些UI元素，如网格线、辅助线等
        // 暂时留空，后续根据需要添加
    }
    
    /**
      * 绘制网格
      */
     private fun drawGrid(canvas: Canvas) {
         val gridSize = 50f * canvasScale
         val startX = (canvasOffsetX % gridSize)
         val startY = (canvasOffsetY % gridSize)
         
         // 绘制垂直线
         var x = startX
         while (x < width) {
             canvas.drawLine(x, 0f, x, height.toFloat(), gridPaint)
             x += gridSize
         }
         
         // 绘制水平线
         var y = startY
         while (y < height) {
             canvas.drawLine(0f, y, width.toFloat(), y, gridPaint)
             y += gridSize
         }
     }
    
    /**
      * 绘制标尺
      */
     private fun drawRuler(canvas: Canvas) {
         val rulerHeight = 30f
         val rulerWidth = 30f
         val tickSize = 10f
         val unitSize = 50f * canvasScale
         
         // 设置标尺背景色
         rulerPaint.color = Color.LTGRAY
         rulerPaint.alpha = 200
         
         // 绘制水平标尺背景
         canvas.drawRect(0f, 0f, width.toFloat(), rulerHeight, rulerPaint)
         
         // 绘制垂直标尺背景
         canvas.drawRect(0f, 0f, rulerWidth, height.toFloat(), rulerPaint)
         
         // 设置刻度线颜色
         rulerPaint.color = Color.GRAY
         rulerPaint.alpha = 255
         
         // 绘制水平标尺刻度
         val startX = (canvasOffsetX % unitSize)
         var x = startX
         var index = 0
         while (x < width) {
             val tickHeight = if (index % 5 == 0) tickSize else tickSize / 2
             canvas.drawLine(x, rulerHeight - tickHeight, x, rulerHeight, rulerPaint)
             
             if (index % 5 == 0) {
                 canvas.drawText("${index * 10}", x + 2, rulerHeight - tickSize - 2, rulerPaint)
             }
             
             x += unitSize / 5
             index++
         }
         
         // 绘制垂直标尺刻度
         val startY = (canvasOffsetY % unitSize)
         var y = startY
         index = 0
         while (y < height) {
             val tickWidth = if (index % 5 == 0) tickSize else tickSize / 2
             canvas.drawLine(rulerWidth - tickWidth, y, rulerWidth, y, rulerPaint)
             
             if (index % 5 == 0) {
                 canvas.save()
                 canvas.rotate(-90f, rulerWidth - tickSize - 2, y)
                 canvas.drawText("${index * 10}", rulerWidth - tickSize - 2, y + 4, rulerPaint)
                 canvas.restore()
             }
             
             y += unitSize / 5
             index++
         }
     }
    
    override fun onTouchEvent(event: MotionEvent): Boolean {
        // 让手势处理器处理触摸事件
        val handled = gestureHandler.handleTouchEvent(event)
        
        // 如果手势处理器处理了事件，刷新画布
        if (handled) {
            invalidate()
        }
        
        return handled || super.onTouchEvent(event)
    }
    
    /**
     * 配置压感响应参数
     */
    private fun configurePressureResponse() {
        if (supportsPressure) {
            // 支持压感的设备
            enablePressureResponse = true
            pressureMinWidth = 0.3f
            pressureMaxWidth = 2.5f
            pressureSensitivity = 1.2f
        } else {
            // 不支持压感的设备
            enablePressureResponse = false
            pressureMinWidth = 1.0f
            pressureMaxWidth = 1.0f
            pressureSensitivity = 1.0f
        }
    }
    
    /**
     * 计算压感响应的笔画宽度
     */
    private fun calculatePressureWidth(baseBrushSize: Float, pressure: Float): Float {
        return if (enablePressureResponse && supportsPressure) {
            val pressureMultiplier = pressureMinWidth + 
                (pressureMaxWidth - pressureMinWidth) * pressure
            baseBrushSize * pressureMultiplier * pressureSensitivity
        } else {
            baseBrushSize
        }
    }
    
    /**
     * 获取压感透明度
     */
    private fun calculatePressureAlpha(baseAlpha: Float, pressure: Float): Float {
        return if (enablePressureResponse && supportsPressure) {
            // 压感影响透明度（轻压更透明）
            val pressureAlpha = 0.3f + 0.7f * pressure
            baseAlpha * pressureAlpha
        } else {
            baseAlpha
        }
    }
    
    /**
     * 设置压感灵敏度
     */
    fun setPressureSensitivity(sensitivity: Float) {
        pressureSensitivity = sensitivity.coerceIn(0.1f, 3.0f)
        pressureHandler.setPressureSensitivity(sensitivity)
    }
    
    /**
     * 设置压感响应范围
     */
    fun setPressureRange(minWidth: Float, maxWidth: Float) {
        pressureMinWidth = minWidth.coerceIn(0.1f, 1.0f)
        pressureMaxWidth = maxWidth.coerceIn(1.0f, 5.0f)
    }
    
    /**
     * 启用/禁用压感响应
     */
    fun setEnablePressureResponse(enabled: Boolean) {
        enablePressureResponse = enabled && supportsPressure
    }
    
    /**
     * 获取压感统计信息
     */
    fun getPressureStatistics(): PressureHandler.PressureStatistics {
        return pressureHandler.getPressureStatistics()
    }
    
    /**
     * 校准压感
     */
    fun calibratePressure(lightPressure: Float, heavyPressure: Float) {
        pressureHandler.calibratePressure(lightPressure, heavyPressure)
    }
    
    /**
     * 重置压感校准
     */
    fun resetPressureCalibration() {
        pressureHandler.resetCalibration()
    }
    
    /**
     * 设置压感变化监听器
     */
    fun setOnPressureChangeListener(listener: (Float) -> Unit) {
        pressureHandler.setOnPressureChangeListener(listener)
    }
    
    /**
     * 处理绘制模式下的触摸事件
     */
    private fun handleDrawingTouch(event: MotionEvent): Boolean {
        // 将屏幕坐标转换为画布坐标
        val canvasPoint = screenToCanvas(event.x, event.y)
        
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                // 开始新的笔画
                startNewStroke(canvasPoint.x, canvasPoint.y, event.pressure)
                return true
            }
            MotionEvent.ACTION_MOVE -> {
                // 继续当前笔画
                continueStroke(canvasPoint.x, canvasPoint.y, event.pressure)
                return true
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                // 结束当前笔画
             finishCurrentStroke()
                return true
            }
        }
        return false
    }
    
    /**
     * 处理导航模式下的触摸事件（拖拽画布）
     */
    private fun handleNavigationTouch(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                lastTouchX = event.x
                lastTouchY = event.y
                return true
            }
            MotionEvent.ACTION_MOVE -> {
                val dx = event.x - lastTouchX
                val dy = event.y - lastTouchY
                
                // 更新画布偏移量
                offsetX += dx
                offsetY += dy
                
                // 更新变换矩阵
                updateCanvasMatrix()
                
                lastTouchX = event.x
                lastTouchY = event.y
                
                // 重绘画布
                invalidate()
                return true
            }
        }
        return false
    }
    

    

    
    /**
     * 结束当前笔画
     */
    private fun finishStroke() {
        currentStroke?.let { stroke ->
            // 通知绘制引擎完成笔画
            drawingEngine.finishStroke(stroke)
            
            // 将笔画添加到画布管理器
            canvasManager.addStroke(stroke)
            
            // 清空当前笔画
            currentStroke = null
            
            // 通知撤销重做状态变化
            onUndoRedoStateChanged?.invoke(canUndo(), canRedo())
            
            // 重绘画布
            invalidate()
        }
    }
    

    
    /**
     * 更新画布变换矩阵
     */
    private fun updateCanvasMatrix() {
        canvasMatrix.reset()
        canvasMatrix.postTranslate(offsetX, offsetY)
        canvasMatrix.postScale(scaleFactor, scaleFactor, width / 2f, height / 2f)
    }
    
    /**
     * 生成唯一的笔画ID
     */
    private fun generateStrokeId(): String {
        return "stroke_${System.currentTimeMillis()}_${hashCode()}"
    }
    
    /**
     * 缩放手势监听器
     */
    private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() {
        override fun onScale(detector: ScaleGestureDetector): Boolean {
            // 计算新的缩放比例
            val newScale = scaleFactor * detector.scaleFactor
            
            // 限制缩放范围
            scaleFactor = max(minScale, min(newScale, maxScale))
            
            // 更新变换矩阵
            updateCanvasMatrix()
            
            // 重绘画布
            invalidate()
            
            return true
        }
    }
    
    // 公共API方法
    
    /**
     * 设置当前绘制工具
     */
    fun setDrawingTool(tool: DrawingTool) {
        if (currentTool != tool) {
            currentTool = tool
            
            // 结束当前笔画
             finishCurrentStroke()
            
            // 根据工具调整相关设置
            when (tool) {
                DrawingTool.PEN -> {
                    // 钢笔：精确绘制，支持压感
                    currentWidth = currentWidth.coerceIn(1f, 20f)
                    setEnablePressureResponse(true)
                    gestureHandler.setGestureMode(GestureHandler.GestureMode.DRAWING)
                }
                DrawingTool.PENCIL -> {
                    // 铅笔：纹理效果，支持压感
                    currentWidth = currentWidth.coerceIn(0.5f, 15f)
                    setEnablePressureResponse(true)
                    gestureHandler.setGestureMode(GestureHandler.GestureMode.DRAWING)
                }
                DrawingTool.HIGHLIGHTER -> {
                    // 荧光笔：较粗，半透明
                    currentWidth = currentWidth.coerceIn(8f, 40f)
                    setEnablePressureResponse(false) // 荧光笔通常不需要压感
                    gestureHandler.setGestureMode(GestureHandler.GestureMode.DRAWING)
                }
                DrawingTool.ERASER -> {
                    // 橡皮擦：可变大小
                    currentWidth = currentWidth.coerceIn(5f, 50f)
                    setEnablePressureResponse(false)
                    gestureHandler.setGestureMode(GestureHandler.GestureMode.ERASING)
                }
            }
            
            invalidate()
        }
    }
    
    /**
     * 设置当前画笔颜色
     */
    fun setDrawingColor(color: Int) {
        if (currentColor != color) {
            // 根据工具调整颜色
            when (currentTool) {
                DrawingTool.HIGHLIGHTER -> {
                    // 荧光笔颜色通常较亮
                    val hsv = FloatArray(3)
                    Color.colorToHSV(color, hsv)
                    hsv[1] = hsv[1] * 0.7f // 降低饱和度
                    hsv[2] = kotlin.math.min(hsv[2] * 1.2f, 1.0f) // 提高亮度
                    currentColor = Color.HSVToColor(hsv)
                }
                DrawingTool.ERASER -> {
                    // 橡皮擦不需要颜色
                    currentColor = Color.TRANSPARENT
                }
                else -> {
                    currentColor = color
                }
            }
            
            // 结束当前笔画
            finishStroke()
            
            invalidate()
        }
    }
    
    /**
     * 设置当前画笔粗细
     */
    fun setDrawingWidth(width: Float) {
        // 根据当前工具限制粗细范围
        val newWidth = when (currentTool) {
            DrawingTool.PEN -> width.coerceIn(1f, 20f)
            DrawingTool.PENCIL -> width.coerceIn(0.5f, 15f)
            DrawingTool.HIGHLIGHTER -> width.coerceIn(8f, 40f)
            DrawingTool.ERASER -> width.coerceIn(5f, 50f)
        }
        
        if (currentWidth != newWidth) {
            currentWidth = newWidth
            
            // 结束当前笔画
            finishStroke()
            
            invalidate()
        }
    }
    
    /**
     * 设置当前工具（别名方法）
     */
    fun setCurrentTool(tool: DrawingTool) {
        setDrawingTool(tool)
    }
    
    /**
     * 设置当前颜色（别名方法）
     */
    fun setCurrentColor(color: Int) {
        setDrawingColor(color)
    }
    
    /**
     * 设置笔画宽度（别名方法）
     */
    fun setStrokeWidth(width: Float) {
        setDrawingWidth(width)
    }
    
    /**
     * 获取当前工具的推荐粗细范围
     */
    fun getRecommendedSizeRange(): Pair<Float, Float> {
        return when (currentTool) {
            DrawingTool.PEN -> Pair(1f, 20f)
            DrawingTool.PENCIL -> Pair(0.5f, 15f)
            DrawingTool.HIGHLIGHTER -> Pair(8f, 40f)
            DrawingTool.ERASER -> Pair(5f, 50f)
        }
    }
    
    /**
     * 获取当前工具信息
     */
    fun getCurrentToolInfo(): ToolInfo {
        return ToolInfo(
            tool = currentTool,
            color = currentColor,
            size = currentWidth,
            supportsPressure = when (currentTool) {
                DrawingTool.PEN, DrawingTool.PENCIL -> true
                else -> false
            },
            alpha = when (currentTool) {
                DrawingTool.HIGHLIGHTER -> 0.4f
                DrawingTool.PENCIL -> 0.7f
                else -> 1.0f
            }
        )
    }
    
    /**
     * 工具信息数据类
     */
    data class ToolInfo(
        val tool: DrawingTool,
        val color: Int,
        val size: Float,
        val supportsPressure: Boolean,
        val alpha: Float
    )
    
    /**
     * 切换绘制模式和导航模式
     */
    fun setDrawingMode(enabled: Boolean) {
        isDrawingMode = enabled
    }
    
    /**
     * 撤销操作
     */
    fun undo(): Boolean {
        val success = canvasManager.undo()
        if (success) {
            // 结束当前笔画
            finishCurrentStroke()
            
            // 刷新画布
            invalidate()
            
            // 通知撤销状态变化
            onUndoRedoStateChanged?.invoke(canUndo(), canRedo())
        }
        return success
    }
    
    /**
     * 重做操作
     */
    fun redo(): Boolean {
        val success = canvasManager.redo()
        if (success) {
            // 结束当前笔画
            finishCurrentStroke()
            
            // 刷新画布
            invalidate()
            
            // 通知撤销状态变化
            onUndoRedoStateChanged?.invoke(canUndo(), canRedo())
        }
        return success
    }
    
    /**
     * 检查是否可以撤销
     */
    fun canUndo(): Boolean {
        return canvasManager.canUndo()
    }
    
    /**
     * 检查是否可以重做
     */
    fun canRedo(): Boolean {
        return canvasManager.canRedo()
    }
    
    /**
     * 获取撤销历史数量
     */
    fun getUndoCount(): Int {
        return canvasManager.getUndoCount()
    }
    
    /**
     * 获取重做历史数量
     */
    fun getRedoCount(): Int {
        return canvasManager.getRedoCount()
    }
    
    /**
     * 清空撤销重做历史
     */
    fun clearHistory() {
        canvasManager.clearHistory()
        onUndoRedoStateChanged?.invoke(canUndo(), canRedo())
    }
    
    /**
     * 撤销重做状态变化回调
     */
    var onUndoRedoStateChanged: ((canUndo: Boolean, canRedo: Boolean) -> Unit)? = null
    
    /**
     * 批量撤销操作
     */
    fun undoMultiple(count: Int): Int {
        var successCount = 0
        repeat(count) {
            if (undo()) {
                successCount++
            } else {
                return@repeat
            }
        }
        return successCount
    }
    
    /**
     * 批量重做操作
     */
    fun redoMultiple(count: Int): Int {
        var successCount = 0
        repeat(count) {
            if (redo()) {
                successCount++
            } else {
                return@repeat
            }
        }
        return successCount
    }
    
    /**
     * 撤销到指定状态
     */
    fun undoToState(targetUndoCount: Int): Boolean {
        val currentCount = getUndoCount()
        if (targetUndoCount >= currentCount) return false
        
        val undoSteps = currentCount - targetUndoCount
        return undoMultiple(undoSteps) == undoSteps
    }
    
    /**
     * 获取撤销重做历史信息
     */
    fun getHistoryInfo(): CanvasManager.HistoryInfo {
        return CanvasManager.HistoryInfo(
            undoCount = getUndoCount(),
            redoCount = getRedoCount(),
            canUndo = canUndo(),
            canRedo = canRedo(),
            maxHistorySize = 50 // 默认最大历史记录数
        )
    }
    
    /**
     * 清空画布
     */
    fun clearCanvas() {
        canvasManager.clear()
        drawingEngine.clear()
        
        // 通知撤销重做状态变化
        onUndoRedoStateChanged?.invoke(canUndo(), canRedo())
        
        invalidate()
    }
    
    /**
      * 开始新的笔画
      */
     private fun startNewStroke(x: Float, y: Float, pressure: Float) {
         // 结束之前的笔画
         finishCurrentStroke()
         
         // 处理压感
         val processedPressure = pressureHandler.processPressure(
             createMotionEvent(x, y, pressure, MotionEvent.ACTION_DOWN)
         )
         
         // 转换屏幕坐标到画布坐标
         val canvasX = (x - canvasOffsetX) / canvasScale
         val canvasY = (y - canvasOffsetY) / canvasScale
         
         if (usePointBasedRendering) {
             // 基于点的绘画逻辑
             val pointSize = calculatePressureWidth(currentWidth, processedPressure)
             val baseAlpha = if (currentTool == DrawingTool.HIGHLIGHTER) 0.5f else 1.0f
             val pressureAlpha = calculatePressureAlpha(baseAlpha, processedPressure)
             
             // 创建起始点
             val startPoint = DrawingPoint(
                 x = canvasX,
                 y = canvasY,
                 pressure = processedPressure,
                 size = pointSize,
                 timestamp = System.currentTimeMillis()
             )
             
             // 创建新的点绘画
             currentPointDrawing = PointDrawing(
                 id = generateStrokeId(),
                 tool = currentTool,
                 color = currentColor,
                 basePointSize = currentWidth,
                 points = listOf(startPoint),
                 timestamp = System.currentTimeMillis(),
                 alpha = pressureAlpha
             )
         } else {
             // 传统线条绘画逻辑
             val startPoint = StrokePoint(
                 x = canvasX,
                 y = canvasY,
                 pressure = processedPressure,
                 timestamp = System.currentTimeMillis()
             )
             
             val pressureWidth = calculatePressureWidth(currentWidth, processedPressure)
             val baseAlpha = if (currentTool == DrawingTool.HIGHLIGHTER) 0.5f else 1.0f
             val pressureAlpha = calculatePressureAlpha(baseAlpha, processedPressure)
             
             currentStroke = Stroke(
                 id = generateStrokeId(),
                 tool = currentTool,
                 color = currentColor,
                 width = pressureWidth,
                 points = listOf(startPoint),
                 timestamp = System.currentTimeMillis(),
                 alpha = pressureAlpha
             )
             
             // 通知绘制引擎开始新笔画
             currentStroke?.let { stroke ->
                 drawingEngine.startStroke(stroke)
             }
         }
         
         isDrawing = true
     }
     
     /**
      * 继续当前笔画
      */
     private fun continueStroke(x: Float, y: Float, pressure: Float) {
        if (!isDrawing) return
        
        // 处理压感
        val processedPressure = pressureHandler.processPressure(
            createMotionEvent(x, y, pressure, MotionEvent.ACTION_MOVE)
        )
        
        // 转换屏幕坐标到画布坐标
        val canvasX = (x - canvasOffsetX) / canvasScale
        val canvasY = (y - canvasOffsetY) / canvasScale
        
        if (usePointBasedRendering) {
            // 基于点的绘画逻辑 - 将连续触摸转换为点阵数据
            currentPointDrawing?.let { pointDrawing ->
                val interpolatedPoints = interpolatePoints(
                    pointDrawing.points.lastOrNull(),
                    canvasX, canvasY, processedPressure
                )
                
                // 由于PointDrawing的points是不可变的，需要重新创建PointDrawing对象
                val newPoints = pointDrawing.points + interpolatedPoints
                currentPointDrawing = pointDrawing.copy(points = newPoints)
            }
        } else {
            // 传统线条绘画逻辑
            if (currentStroke == null) return
            
            val newPoint = StrokePoint(
                x = canvasX,
                y = canvasY,
                pressure = processedPressure,
                timestamp = System.currentTimeMillis()
            )
            
            // 由于Stroke的points是不可变的，需要重新创建Stroke对象
            currentStroke?.let { stroke ->
                val newPoints = stroke.points + newPoint
                val newWidth = if (enablePressureResponse && supportsPressure) {
                    calculatePressureWidth(currentWidth, processedPressure)
                } else {
                    stroke.width
                }
                
                currentStroke = stroke.copy(
                    points = newPoints,
                    width = newWidth
                )
                
                // 通知绘制引擎更新笔画
                drawingEngine.updateStroke(currentStroke!!)
            }
        }

        // 触发重绘以实现实时显示
        invalidate()
    }
     
     /**
     * 完成当前笔画
     */
     private fun finishCurrentStroke() {
         if (!isDrawing) return
         
         if (usePointBasedRendering) {
             // 基于点的绘画逻辑
             currentPointDrawing?.let { pointDrawing ->
                 // 添加点绘画到画布管理器
                 canvasManager.addPointDrawing(pointDrawing)
                 
                 // 清理当前点绘画
                 currentPointDrawing = null
                 isDrawing = false
                 
                 // 通知撤销重做状态变化
                 onUndoRedoStateChanged?.invoke(canUndo(), canRedo())
                 
                 // 刷新画布
                 invalidate()
             }
         } else {
             // 传统线条绘画逻辑
             currentStroke?.let { stroke ->
                 // 添加笔画到画布管理器
                 canvasManager.addStroke(stroke)
                 
                 // 清理当前笔画
                 currentStroke = null
                 isDrawing = false
                 
                 // 通知撤销重做状态变化
                 onUndoRedoStateChanged?.invoke(canUndo(), canRedo())
                 
                 // 刷新画布
                 invalidate()
             }
         }
     }
     
     /**
      * 执行擦除操作
      */
     private fun performErase(x: Float, y: Float) {
         // 转换屏幕坐标到画布坐标
         val canvasX = (x - canvasOffsetX) / canvasScale
         val canvasY = (y - canvasOffsetY) / canvasScale
         
         // 获取擦除半径
         val eraseRadius = currentBrushSize / 2f
         
         // 查找需要擦除的笔画
         val strokesToRemove = canvasManager.getAllStrokes().filter { stroke: Stroke ->
             stroke.points.any { point: StrokePoint ->
                 val distance = kotlin.math.sqrt(
                     (point.x - canvasX) * (point.x - canvasX) + 
                     (point.y - canvasY) * (point.y - canvasY)
                 )
                 distance <= eraseRadius
             }
         }
         
         // 移除笔画
         strokesToRemove.forEach { stroke: Stroke ->
             canvasManager.removeStroke(stroke.id)
         }
         
         // 如果有笔画被移除，刷新画布
         if (strokesToRemove.isNotEmpty()) {
             invalidate()
         }
     }
     
     /**
      * 创建MotionEvent用于压感处理
      */
     /**
     * 在两个点之间插值生成点阵数据
     * @param lastPoint 上一个点，如果为null则直接返回当前点
     * @param currentX 当前点的X坐标
     * @param currentY 当前点的Y坐标
     * @param currentPressure 当前点的压感值
     * @return 插值生成的点列表
     */
    private fun interpolatePoints(
        lastPoint: DrawingPoint?,
        currentX: Float,
        currentY: Float,
        currentPressure: Float
    ): List<DrawingPoint> {
        val currentTimestamp = System.currentTimeMillis()
        val currentPoint = DrawingPoint(
            x = currentX,
            y = currentY,
            pressure = currentPressure,
            timestamp = currentTimestamp
        )
        
        // 如果没有上一个点，直接返回当前点
        if (lastPoint == null) {
            return listOf(currentPoint)
        }
        
        // 计算两点间的距离
        val deltaX = currentX - lastPoint.x
        val deltaY = currentY - lastPoint.y
        val distance = kotlin.math.sqrt(deltaX * deltaX + deltaY * deltaY)
        
        // 根据画布缩放调整插值密度
        val baseStepSize = 2.0f // 基础步长（画布坐标）
        val stepSize = baseStepSize / canvasScale // 根据缩放调整步长
        
        // 如果距离太小，不需要插值
        if (distance <= stepSize) {
            return listOf(currentPoint)
        }
        
        // 计算需要插值的点数
        val numSteps = (distance / stepSize).toInt()
        val interpolatedPoints = mutableListOf<DrawingPoint>()
        
        // 生成插值点
        for (i in 1..numSteps) {
            val t = i.toFloat() / (numSteps + 1)
            val interpolatedX = lastPoint.x + deltaX * t
            val interpolatedY = lastPoint.y + deltaY * t
            val interpolatedPressure = lastPoint.pressure + (currentPressure - lastPoint.pressure) * t
            val interpolatedTimestamp = lastPoint.timestamp + ((currentTimestamp - lastPoint.timestamp) * t).toLong()
            
            interpolatedPoints.add(
                DrawingPoint(
                    x = interpolatedX,
                    y = interpolatedY,
                    pressure = interpolatedPressure,
                    timestamp = interpolatedTimestamp
                )
            )
        }
        
        // 添加当前点
        interpolatedPoints.add(currentPoint)
        
        return interpolatedPoints
    }
    
    private fun createMotionEvent(x: Float, y: Float, pressure: Float, action: Int): MotionEvent {
         val downTime = System.currentTimeMillis()
         val eventTime = downTime
         return MotionEvent.obtain(
             downTime, eventTime, action, x, y, pressure, 1.0f, 0, 1.0f, 1.0f, 0, 0
         )
     }
     
     // 手势相关变量
    private var panStartX = 0f
    private var panStartY = 0f
    private var scaleStartX = 0f
    private var scaleStartY = 0f
    private var minCanvasScale = 0.1f
    private var maxCanvasScale = 10.0f
    private var canvasScale = 1.0f
    private var canvasOffsetX = 0f
    private var canvasOffsetY = 0f
    private var isDrawing = false
    private var currentBrushSize = 6f
    
    // 变换矩阵
    private val canvasTransform = Matrix()
    private val inverseTransform = Matrix()
    
    // 动画相关
    private var scaleAnimator: ValueAnimator? = null
    private var flingAnimator: ValueAnimator? = null
    
    // 手势模式变化回调
    var onGestureModeChanged: ((GestureHandler.GestureMode) -> Unit)? = null
    
    // 橡皮擦相关变量
    private var eraserMode = EraserMode.SMART
    private var eraserSize = 20f
    private var eraserSensitivity = 0.5f
    
    // 网格和标尺显示
    private var showGrid = false
    private var showRuler = false
    private val gridPaint = Paint().apply {
        color = Color.LTGRAY
        strokeWidth = 1f
        alpha = 128
    }
    private val rulerPaint = Paint().apply {
        color = Color.GRAY
        strokeWidth = 2f
        textSize = 24f
    }
    
    /**
     * 橡皮擦模式枚举
     */
    enum class EraserMode {
        STROKE,  // 笔画擦除 - 擦除整个笔画
        PIXEL,   // 像素擦除 - 擦除笔画的部分区域
        SMART    // 智能擦除 - 根据情况自动选择擦除方式
    }
    
    /**
     * 手势处理器回调实现
     */
    private val gestureCallback = object : GestureHandler.GestureCallback {
        override fun onDrawingStart(x: Float, y: Float, pressure: Float) {
            startNewStroke(x, y, pressure)
        }
        
        override fun onDrawingMove(x: Float, y: Float, pressure: Float) {
            continueStroke(x, y, pressure)
        }
        
        override fun onDrawingEnd() {
            finishCurrentStroke()
        }
        
        override fun onCanvasDrag(dx: Float, dy: Float) {
            // 应用平移变换
            canvasTransform.postTranslate(dx, dy)
            canvasOffsetX += dx
            canvasOffsetY += dy
            
            // 限制平移范围
            constrainTransform()
            
            invalidate()
        }
        
        override fun onCanvasScale(scaleFactor: Float, focusX: Float, focusY: Float) {
            // 应用缩放变换
            canvasTransform.postScale(scaleFactor, scaleFactor, focusX, focusY)
            val newScale = canvasScale * scaleFactor
            canvasScale = max(minCanvasScale, min(newScale, maxCanvasScale))
            
            // 限制缩放范围
            constrainTransform()
            
            invalidate()
        }
        
        override fun onCanvasDoubleTap(x: Float, y: Float) {
            // 双击缩放
            val currentScale = getCurrentScale()
            val targetScale = if (currentScale > 1.5f) 1.0f else 2.5f
            animateScaleTo(targetScale, x, y)
        }
        
        override fun onToolLongPress(x: Float, y: Float) {
            // 长按处理 - 可用于显示上下文菜单
            performLongClick()
        }
        
        override fun onEraserMove(x: Float, y: Float) {
            eraseAtPoint(x, y, eraserSize)
        }
        
        override fun onPanStart(x: Float, y: Float) {
            // 记录平移开始位置
            panStartX = x
            panStartY = y
        }
        

        
        override fun onPanEnd(velocityX: Float, velocityY: Float) {
            // 应用惯性滑动
            if (Math.abs(velocityX) > 500 || Math.abs(velocityY) > 500) {
                startFlingAnimation(velocityX, velocityY)
            }
        }
        
        override fun onScaleStart(focusX: Float, focusY: Float) {
            // 记录缩放焦点
            scaleStartX = focusX
            scaleStartY = focusY
        }
        

        
        override fun onScaleEnd(velocity: Float) {
            // 缩放结束后的处理
            val currentScale = getCurrentScale()
            
            // 如果缩放过小或过大，自动调整
            if (currentScale < minCanvasScale) {
                animateScaleTo(minCanvasScale, scaleStartX, scaleStartY)
            } else if (currentScale > maxCanvasScale) {
                animateScaleTo(maxCanvasScale, scaleStartX, scaleStartY)
            }
        }
        

        
        override fun onFling(velocityX: Float, velocityY: Float) {
            // 快速滑动处理
            startFlingAnimation(velocityX * 0.3f, velocityY * 0.3f)
        }
        
        override fun onGestureStateChanged(newMode: GestureHandler.GestureMode) {
            // 手势模式变化处理
            onGestureModeChanged?.invoke(newMode)
        }
        
        override fun onGestureModeChanged(mode: GestureHandler.GestureMode) {
            // 手势模式变化处理
            onGestureModeChanged?.invoke(mode)
        }
    }
    
    /**
     * 限制变换范围
     */
    private fun constrainTransform() {
        // 限制缩放范围
        val currentScale = getCurrentScale()
        if (currentScale < minCanvasScale || currentScale > maxCanvasScale) {
            val constrainedScale = max(minCanvasScale, min(currentScale, maxCanvasScale))
            val scaleRatio = constrainedScale / currentScale
            canvasTransform.postScale(scaleRatio, scaleRatio, width / 2f, height / 2f)
            canvasScale = constrainedScale
        }
    }
    
    /**
     * 获取当前缩放比例
     */
    private fun getCurrentScale(): Float {
        val values = FloatArray(9)
        canvasTransform.getValues(values)
        return values[Matrix.MSCALE_X]
    }
    
    /**
     * 动画缩放到指定比例
     */
    private fun animateScaleTo(targetScale: Float, focusX: Float, focusY: Float) {
        scaleAnimator?.cancel()
        
        val currentScale = getCurrentScale()
        scaleAnimator = ValueAnimator.ofFloat(currentScale, targetScale).apply {
            duration = 300
            addUpdateListener { animator ->
                val scale = animator.animatedValue as Float
                val scaleRatio = scale / getCurrentScale()
                canvasTransform.postScale(scaleRatio, scaleRatio, focusX, focusY)
                canvasScale = scale
                invalidate()
            }
            start()
        }
    }
    
    /**
     * 开始惯性滑动动画
     */
    private fun startFlingAnimation(velocityX: Float, velocityY: Float) {
        flingAnimator?.cancel()
        
        flingAnimator = ValueAnimator.ofFloat(1f, 0f).apply {
            duration = 1000
            addUpdateListener { animator ->
                val factor = animator.animatedValue as Float
                val dx = velocityX * factor * 0.016f // 假设16ms每帧
                val dy = velocityY * factor * 0.016f
                
                canvasTransform.postTranslate(dx, dy)
                canvasOffsetX += dx
                canvasOffsetY += dy
                invalidate()
            }
            start()
        }
    }
    
    /**
      * 在指定点执行擦除操作
      */
     private fun eraseAtPoint(x: Float, y: Float, radius: Float) {
         when (eraserMode) {
             EraserMode.STROKE -> eraseStrokeAtPoint(x, y, radius)
             EraserMode.PIXEL -> erasePixelAtPoint(x, y, radius)
             EraserMode.SMART -> smartEraseAtPoint(x, y, radius)
         }
     }
     
     /**
      * 笔画擦除模式 - 擦除整个笔画
      */
     private fun eraseStrokeAtPoint(x: Float, y: Float, radius: Float) {
         val canvasPoint = screenToCanvas(x, y)
         
         val strokesToRemove = canvasManager.getVisibleStrokes(RectF(
             canvasPoint.x - radius, canvasPoint.y - radius,
             canvasPoint.x + radius, canvasPoint.y + radius
         )).filter { stroke ->
             isStrokeIntersectingCircle(stroke, canvasPoint.x, canvasPoint.y, radius)
         }
         
         strokesToRemove.forEach { stroke ->
             canvasManager.removeStroke(stroke.id)
         }
         
         if (strokesToRemove.isNotEmpty()) {
             onUndoRedoStateChanged?.invoke(canUndo(), canRedo())
             invalidate()
         }
     }
     
     /**
      * 像素擦除模式 - 擦除笔画的部分区域
      */
     private fun erasePixelAtPoint(x: Float, y: Float, radius: Float) {
         val canvasPoint = screenToCanvas(x, y)
         val erasedStrokes = mutableListOf<Stroke>()
         val newStrokes = mutableListOf<Stroke>()
         
         val affectedStrokes = canvasManager.getVisibleStrokes(RectF(
             canvasPoint.x - radius, canvasPoint.y - radius,
             canvasPoint.x + radius, canvasPoint.y + radius
         )).filter { stroke ->
             isStrokeIntersectingCircle(stroke, canvasPoint.x, canvasPoint.y, radius)
         }
         
         affectedStrokes.forEach { stroke ->
             val segments = splitStrokeByEraser(stroke, canvasPoint.x, canvasPoint.y, radius)
             if (segments.isNotEmpty()) {
                 erasedStrokes.add(stroke)
                 newStrokes.addAll(segments)
             }
         }
         
         // 批量操作以提高性能
         if (erasedStrokes.isNotEmpty()) {
             erasedStrokes.forEach { canvasManager.removeStroke(it.id) }
             newStrokes.forEach { canvasManager.addStroke(it) }
             
             onUndoRedoStateChanged?.invoke(canUndo(), canRedo())
             invalidate()
         }
     }
     
     /**
      * 智能擦除模式 - 根据笔画密度和类型智能选择擦除方式
      */
     private fun smartEraseAtPoint(x: Float, y: Float, radius: Float) {
         val canvasPoint = screenToCanvas(x, y)
         val affectedStrokes = canvasManager.getVisibleStrokes(RectF(
             canvasPoint.x - radius * 2, canvasPoint.y - radius * 2,
             canvasPoint.x + radius * 2, canvasPoint.y + radius * 2
         ))
         
         // 分析擦除区域的笔画密度
         val strokeDensity = calculateStrokeDensity(affectedStrokes, canvasPoint.x, canvasPoint.y, radius)
         
         when {
             strokeDensity > 0.7f -> {
                 // 高密度区域，使用像素擦除
                 erasePixelAtPoint(x, y, radius)
             }
             strokeDensity > 0.3f -> {
                 // 中密度区域，使用混合擦除
                 mixedEraseAtPoint(x, y, radius)
             }
             else -> {
                 // 低密度区域，使用笔画擦除
                 eraseStrokeAtPoint(x, y, radius)
             }
         }
     }
     
     /**
      * 混合擦除模式
      */
     private fun mixedEraseAtPoint(x: Float, y: Float, radius: Float) {
         val canvasPoint = screenToCanvas(x, y)
         val affectedStrokes = canvasManager.getVisibleStrokes(RectF(
             canvasPoint.x - radius, canvasPoint.y - radius,
             canvasPoint.x + radius, canvasPoint.y + radius
         ))
         
         val strokesToRemove = mutableListOf<Stroke>()
         val strokesToSplit = mutableListOf<Stroke>()
         val newStrokes = mutableListOf<Stroke>()
         
         affectedStrokes.forEach { stroke ->
             val intersectionRatio = calculateStrokeIntersectionRatio(stroke, canvasPoint.x, canvasPoint.y, radius)
             
             when {
                 intersectionRatio > 0.8f -> {
                     // 大部分被擦除，直接删除整个笔画
                     strokesToRemove.add(stroke)
                 }
                 intersectionRatio > 0.1f -> {
                     // 部分被擦除，分割笔画
                     strokesToSplit.add(stroke)
                 }
             }
         }
         
         // 处理分割的笔画
         strokesToSplit.forEach { stroke ->
             val segments = splitStrokeByEraser(stroke, canvasPoint.x, canvasPoint.y, radius)
             if (segments.isNotEmpty()) {
                 strokesToRemove.add(stroke)
                 newStrokes.addAll(segments)
             }
         }
         
         // 批量操作
         if (strokesToRemove.isNotEmpty() || newStrokes.isNotEmpty()) {
             strokesToRemove.forEach { canvasManager.removeStroke(it.id) }
             newStrokes.forEach { canvasManager.addStroke(it) }
             
             onUndoRedoStateChanged?.invoke(canUndo(), canRedo())
             invalidate()
         }
     }
     
     /**
      * 屏幕坐标转画布坐标
      */
     private fun screenToCanvas(screenX: Float, screenY: Float): PointF {
         val point = floatArrayOf(screenX, screenY)
         canvasTransform.invert(inverseTransform)
         inverseTransform.mapPoints(point)
         return PointF(point[0], point[1])
     }
     
     /**
      * 画布坐标转屏幕坐标
      */
     private fun canvasToScreen(canvasX: Float, canvasY: Float): PointF {
         val point = floatArrayOf(canvasX, canvasY)
         canvasTransform.mapPoints(point)
         return PointF(point[0], point[1])
     }
     
     /**
      * 设置缩放范围
      */
     fun setScaleRange(minScale: Float, maxScale: Float) {
         minCanvasScale = minScale.coerceAtLeast(0.01f)
         maxCanvasScale = maxScale.coerceAtMost(50.0f)
         gestureHandler.setScaleRange(minCanvasScale, maxCanvasScale)
     }
     
     /**
      * 重置画布变换
      */
     fun resetTransform() {
         scaleAnimator?.cancel()
         flingAnimator?.cancel()
         
         canvasTransform.reset()
         canvasScale = 1.0f
         canvasOffsetX = 0f
         canvasOffsetY = 0f
         invalidate()
     }
     
     /**
      * 获取画布变换信息
      */
     fun getTransformInfo(): TransformInfo {
         return TransformInfo(
             scale = getCurrentScale(),
             offsetX = canvasOffsetX,
             offsetY = canvasOffsetY,
             minScale = minCanvasScale,
             maxScale = maxCanvasScale
         )
     }
     
     /**
      * 画布变换信息数据类
      */
     data class TransformInfo(
         val scale: Float,
         val offsetX: Float,
         val offsetY: Float,
         val minScale: Float,
         val maxScale: Float
     )
     
     /**
      * 检查笔画是否与圆形区域相交
      */
     private fun isStrokeIntersectingCircle(stroke: Stroke, centerX: Float, centerY: Float, radius: Float): Boolean {
         return stroke.points.any { point ->
             val distance = kotlin.math.sqrt(
                 (point.x - centerX) * (point.x - centerX) + 
                 (point.y - centerY) * (point.y - centerY)
             )
             distance <= radius + stroke.width / 2
         }
     }
     
     /**
      * 计算笔画与擦除区域的相交比例
      */
     private fun calculateStrokeIntersectionRatio(stroke: Stroke, centerX: Float, centerY: Float, radius: Float): Float {
         val totalPoints = stroke.points.size
         if (totalPoints == 0) return 0f
         
         val intersectingPoints = stroke.points.count { point ->
             val distance = kotlin.math.sqrt(
                 (point.x - centerX) * (point.x - centerX) + 
                 (point.y - centerY) * (point.y - centerY)
             )
             distance <= radius
         }
         
         return intersectingPoints.toFloat() / totalPoints
     }
     
     /**
      * 根据擦除区域分割笔画
      */
     private fun splitStrokeByEraser(stroke: Stroke, centerX: Float, centerY: Float, radius: Float): List<Stroke> {
         val segments = mutableListOf<Stroke>()
         val currentSegment = mutableListOf<StrokePoint>()
         
         stroke.points.forEach { point ->
             val distance = kotlin.math.sqrt(
                 (point.x - centerX) * (point.x - centerX) + 
                 (point.y - centerY) * (point.y - centerY)
             )
             
             if (distance > radius) {
                 // 点在擦除区域外，添加到当前段
                 currentSegment.add(point)
             } else {
                 // 点在擦除区域内，结束当前段
                 if (currentSegment.size >= 2) {
                     segments.add(createStrokeFromPoints(currentSegment, stroke))
                 }
                 currentSegment.clear()
             }
         }
         
         // 处理最后一段
         if (currentSegment.size >= 2) {
             segments.add(createStrokeFromPoints(currentSegment, stroke))
         }
         
         return segments
     }
     
     /**
      * 从点列表创建新的笔画
      */
     private fun createStrokeFromPoints(points: List<StrokePoint>, originalStroke: Stroke): Stroke {
         return Stroke(
             id = generateStrokeId(),
             points = points,
             color = originalStroke.color,
             width = originalStroke.width,
             tool = originalStroke.tool,
             timestamp = System.currentTimeMillis(),
             alpha = originalStroke.alpha
         )
     }
     
     /**
      * 计算区域内的笔画密度
      */
     private fun calculateStrokeDensity(strokes: List<Stroke>, centerX: Float, centerY: Float, radius: Float): Float {
         if (strokes.isEmpty()) return 0f
         
         val area = Math.PI * radius * radius
         var totalLength = 0f
         
         strokes.forEach { stroke ->
             var strokeLength = 0f
             for (i in 1 until stroke.points.size) {
                 val p1 = stroke.points[i - 1]
                 val p2 = stroke.points[i]
                 
                 // 检查线段是否与圆形区域相交
                 if (isLineIntersectingCircle(p1.x, p1.y, p2.x, p2.y, centerX, centerY, radius)) {
                     val segmentLength = kotlin.math.sqrt(
                         (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)
                     )
                     strokeLength += segmentLength
                 }
             }
             totalLength += strokeLength
         }
         
         // 密度 = 总长度 / 区域面积
         return (totalLength / area.toFloat()).coerceIn(0f, 1f)
     }
     
     /**
      * 检查线段是否与圆形相交
      */
     private fun isLineIntersectingCircle(
         x1: Float, y1: Float, x2: Float, y2: Float,
         centerX: Float, centerY: Float, radius: Float
     ): Boolean {
         // 计算线段到圆心的最短距离
         val dx = x2 - x1
         val dy = y2 - y1
         val length = kotlin.math.sqrt(dx * dx + dy * dy)
         
         if (length == 0f) {
             // 线段退化为点
             val distance = kotlin.math.sqrt(
                 (x1 - centerX) * (x1 - centerX) + (y1 - centerY) * (y1 - centerY)
             )
             return distance <= radius
         }
         
         val t = ((centerX - x1) * dx + (centerY - y1) * dy) / (length * length)
         val clampedT = t.coerceIn(0f, 1f)
         
         val closestX = x1 + clampedT * dx
         val closestY = y1 + clampedT * dy
         
         val distance = kotlin.math.sqrt(
             (closestX - centerX) * (closestX - centerX) + 
             (closestY - centerY) * (closestY - centerY)
         )
         
         return distance <= radius
     }
     

     
     /**
      * 设置橡皮擦模式
      */
     fun setEraserMode(mode: EraserMode) {
         eraserMode = mode
     }
     
     /**
      * 设置橡皮擦大小
      */
     fun setEraserSize(size: Float) {
         eraserSize = size.coerceIn(5f, 100f)
     }
     
     /**
      * 设置橡皮擦灵敏度
      */
     fun setEraserSensitivity(sensitivity: Float) {
         eraserSensitivity = sensitivity.coerceIn(0.1f, 1.0f)
     }
     
     /**
      * 获取橡皮擦信息
      */
     fun getEraserInfo(): EraserInfo {
         return EraserInfo(
             mode = eraserMode,
             size = eraserSize,
             sensitivity = eraserSensitivity
         )
     }
     
     /**
      * 橡皮擦信息数据类
      */
     data class EraserInfo(
         val mode: EraserMode,
         val size: Float,
         val sensitivity: Float
     )
    
    /**
     * 创建手势监听器
     */
    private fun createGestureListener(): GestureHandler.GestureCallback {
        return object : GestureHandler.GestureCallback {
            override fun onDrawingStart(x: Float, y: Float, pressure: Float) {
                 startNewStroke(x, y, pressure)
             }
             
             override fun onDrawingMove(x: Float, y: Float, pressure: Float) {
                 continueStroke(x, y, pressure)
             }
             
             override fun onDrawingEnd() {
                 finishCurrentStroke()
             }
             
             override fun onCanvasDrag(dx: Float, dy: Float) {
                 canvasOffsetX += dx
                 canvasOffsetY += dy
                 invalidate()
             }
             
             override fun onCanvasScale(scaleFactor: Float, focusX: Float, focusY: Float) {
                 val newScale = canvasScale * scaleFactor
                 canvasScale = max(minCanvasScale, min(newScale, maxCanvasScale))
                 invalidate()
             }
             
             override fun onCanvasDoubleTap(x: Float, y: Float) {
                 // 双击重置缩放
                 canvasScale = 1.0f
                 canvasOffsetX = 0f
                 canvasOffsetY = 0f
                 invalidate()
             }
             
             override fun onToolLongPress(x: Float, y: Float) {
                 // 长按切换工具
             }
             
             override fun onEraserMove(x: Float, y: Float) {
                 performErase(x, y)
             }
             
             override fun onGestureModeChanged(mode: GestureHandler.GestureMode) {
                 // 手势模式变更
             }
             
             override fun onPanStart(x: Float, y: Float) {
                 // 平移开始
             }
             
             override fun onPanEnd(velocityX: Float, velocityY: Float) {
                 // 平移结束
             }
             
             override fun onScaleStart(focusX: Float, focusY: Float) {
                 // 缩放开始
             }
             
             override fun onScaleEnd(velocity: Float) {
                 // 缩放结束
             }
             
             override fun onFling(velocityX: Float, velocityY: Float) {
                 // 惯性滑动
             }
             
             override fun onGestureStateChanged(newMode: GestureHandler.GestureMode) {
                 // 手势状态变更
             }
        }
    }
    
    /**
     * 设置网格显示状态
     */
    fun setGridVisible(visible: Boolean) {
        showGrid = visible
        invalidate()
    }
    
    /**
     * 获取网格显示状态
     */
    fun isGridVisible(): Boolean = showGrid
    
    /**
     * 设置标尺显示状态
     */
    fun setRulerVisible(visible: Boolean) {
        showRuler = visible
        invalidate()
    }
    
    /**
     * 获取标尺显示状态
     */
    fun isRulerVisible(): Boolean = showRuler
    
    /**
     * 获取画布数据（用于保存）
     */
    fun getCanvasData(): String {
        // TODO: 实现画布数据序列化
        return ""
    }
    
    /**
     * 设置画布数据（用于加载）
     */
    fun setCanvasData(data: String) {
        // TODO: 实现画布数据反序列化
        invalidate()
    }
    
    /**
     * 画布状态变化监听器
     */
    interface OnCanvasStateChangeListener {
        fun onZoomChanged(scale: Float)
        fun onPositionChanged(x: Float, y: Float)
        fun onStrokeAdded(stroke: Stroke)
        fun onStrokeRemoved(stroke: Stroke)
        fun onCanvasCleared()
    }
    
    private var canvasStateChangeListener: OnCanvasStateChangeListener? = null
    
    /**
     * 设置画布状态变化监听器
     */
    fun setOnCanvasStateChangeListener(listener: OnCanvasStateChangeListener?) {
        canvasStateChangeListener = listener
    }
}